class Bullet extends GridBase {
	public dir: TankDir;
	public onDestory: Function;
	public target: Tank;
	static bulletList: { [k: number]: Bullet } = {};
	private speed = 10;
	public constructor() {
		super();
		this.img.source = "bullet_png";
		this.anchorOffsetX = 5;
		this.anchorOffsetY = 5;
		this.gridH = 2;
		this.gridV = 2;
		this.offsetH = -1;
		this.offsetV = -1;
	}
	/**舞台边界碰撞 */
	private stateBoundCheck() {
		if (this.x <= 0 || this.x >= this.stage.stageWidth || this.y <= 0 || this.y >= this.stage.stageHeight) {
			return true;
		}
	}
	/**与阻挡物碰撞 */
	private mapBoundCheck() {
		let myGrid = this.getSideGrid(this.dir, this.dir % 2 == 0 ? -1 : 0);
		let isCollide = false;
		for (var index of myGrid) {
			let ele = MapElement.getElement(index)
			if (ele && ele.isBlock()) {
				MapElement.breakElement(index);
				isCollide = true;
			}
		}
		return isCollide;
	}
	/**与坦克碰撞 */
	tankBoundCheck() {
		let myGrid = this.getGrid();
		let tanks = TankMap.ins.getTank();
		for (let tank of tanks) {
			if (tank && !tank.isDead && tank.team != this.target.team) {
				if (GridBase.contains(myGrid, tank.getGrid())) {
					tank.unHit();
					return true;
				}
			}
		}
	}

	/**子弹抵消子弹 */
	bulletCheck() {
		let myGrid = this.getGrid();
		for (var key in Bullet.bulletList) {
			let bullets = Bullet.bulletList[key];
			if (this.target.team != bullets.target.team) {
				if (GridBase.contains(myGrid, bullets.getGrid())) {
					bullets.clear();
					return true;
				}
			}
		}
	}
	private update() {
		switch (this.dir) {
			case TankDir.Up:
				this.y -= this.speed;
				break;
			case TankDir.Down:
				this.y += this.speed;
				break;
			case TankDir.Left:
				this.x -= this.speed;
				break;
			case TankDir.Right:
				this.x += this.speed;
				break;
			default:
				break;
		}
		if (this.stateBoundCheck() || this.mapBoundCheck() || this.tankBoundCheck() || this.bulletCheck()) {
			this.clear();
		}
	}
	$onAddToStage(stage: egret.Stage, nestLevel: number) {
		Bullet.bulletList[this.hashCode] = this;
		this.addEventListener(egret.Event.ENTER_FRAME, this.update, this);
		super.$onAddToStage(stage, nestLevel);
	}
	$onRemoveFromStage() {
		this.removeEventListener(egret.Event.ENTER_FRAME, this.update, this);
		this.onDestory && this.onDestory();
		delete Bullet.bulletList[this.hashCode];
		super.$onRemoveFromStage()
	}
}